import { message } from "antd"
import { useEffect } from "react"
import { useNavigate } from "react-router-dom"
import useLayoutStore from "../store/layoutStore"

const AuthRoute = ({ children, auth }: any) => {
  const navigate = useNavigate()

  const getToken = localStorage.getItem('useUserStore')
  const token = getToken ? JSON.parse(getToken).state.token : ''

  useEffect(() => {
    if (token == "") {
      if (location.pathname === '/login') {
        navigate(location.pathname)
      } else {
        navigate('/login')
      }
    }
    if (token) {
      const { getMenus, isLoadingMenus, setLoadingMenus } = useLayoutStore.getState()
      if (location.pathname === '/' || location.pathname === '/login') {
        getMenus()
        navigate('/home')
      } else {
        if (!isLoadingMenus) {
          getMenus()
          setLoadingMenus(true)
        }
        navigate(location.pathname)
      }
    }
  }, [token])
  return children
}

export default AuthRoute